<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="设备名称" prop="equipName">
        <el-input
          v-model="queryParams.equipName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理状态" prop="handleState">
        <el-select v-model="queryParams.handleState" placeholder="请选择处理状态" clearable>
          <el-option
            v-for="dict in dict.type.handle_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <br>
      <el-form-item label="请选择日期" prop="createTime">
        <div class="">
          <el-date-picker
            v-model="createTime"
            type="daterange"
            align="right"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateFormat"
          >
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:alarm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" width="60"/>
      <el-table-column label="设备名称" align="center" prop="equipName" />
      <el-table-column label="sn序号" align="center" prop="snNum" />
      <el-table-column label="所属区域" align="center" prop="region" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="数据类型" align="center" prop="dataType" />
      <el-table-column label="触发器名称" align="center" prop="trigerName" />
      <el-table-column label="报警值" align="center" prop="warningValue" width="60" >
        <template slot-scope="scope">
          <div :style="{ color: scope.row.warningValue !=' '?'red':'black'}">
            {{ scope.row.warningValue }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="阈值" align="center" prop="threshold" width="60"/>
      <el-table-column label="处理状态" align="center" prop="handleState" >
        <template slot-scope="scope" style="text-align: left">
          <div v-if="scope.row.handleState == '未处理'">未处理</div>
          <div v-if="scope.row.handleState == '已处理'">已处理</div>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="status" />
      <el-table-column label="报警时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="处理时间" align="center" prop="handleTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          处理按钮-->
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:alarm:edit']"
          >
            <i class="fa fa-play-circle-o fa-1x" aria-hidden="true"></i>
            <span v-if="scope.row.handleState == '未处理'">处理 </span>
          </el-button>
<!--          查看详情按钮-->
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate1(scope.row)"
            v-hasPermi="['system:alarm:edit']"
          >
            <i class="fa fa-play-circle-o fa-1x" aria-hidden="true"></i>
            <span v-if="scope.row.handleState == '已处理'">查看详情</span>
          </el-button>
          <el-button
            size="mini"
            type="text"
            class="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:alarm:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改报警对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" enctype="multipart/form-data" >
        <el-form-item label="备注" prop="notes">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.notes">
          </el-input>
        </el-form-item>

        <el-form-item label="处理图片" prop="handlePicture" label-width="40">
          <el-upload
            :action="imgUpload.url"
            :headers="imgUpload.headers"
            list-type="picture-card"
            :on-success="handlePictureSuccess"
            :on-preview="handlePictureCardPreview"
            :on-change="uploadChange"

            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" v-if="imageUrl" :src="imageUrl" alt="">
          </el-dialog>
        </el-form-item>


      </el-form>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--      查看详情页面-->
    <el-dialog :title="title" :visible.sync="opens" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="85px" enctype="multipart/form-data">

        <el-form-item label="当前处理人" prop="handlePeople">
          <el-input
            placeholder="请输入内容"
            v-model="form.handlePeople"
            :disabled="true">
          </el-input>
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.notes"
            :disabled="true">
          </el-input>
        </el-form-item>

        <el-form-item label="处理图片" prop="handlePicture" label-width="40">
          <el-upload
            :action="imgUpload.url"
            :headers="imgUpload.headers"
            list-type="picture-card"
            :on-success="handlePictureSuccess"
            :on-preview="handlePictureCardPreview"
            :file-list="fileList"
            :disabled="true"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" v-if="imageUrl" :src="imageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>

    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData, addData, updateData } from "@/api/system/alarm";
import MyComponent from '../../components/MyComponent.vue'
import FileUpload from "@/components/FileUpload/index.vue";
import {upLoad} from "@/api/system/manage";
//记得导入 getToken
import { getToken } from "@/utils/auth";
export default {
  components:{
    'my-component': MyComponent,
    'file':FileUpload
  },
  name: "Data",
  dicts: ['handle_state','status'],
  data() {
    return {
      disabled: false,
      dialogVisible: false,
      dialogImageUrl: '',
      fileList:[],
      //图片地址
      imageUrl: "",

      hideUpload: false,
      // uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/alarm/uploadFileUrl", // 上传的图片服务器地址

      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/system/alarm/articleImg",
      },
      handlePicture:[],//处理图片
      headFile: '',
      headFileList: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      opens: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipName: null,
        handleState: null,
        status: null,
      },
      createTime:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        notes: [
          { required: true, message: "备注不能为空", trigger: "blur" },
        ],
        handlePicture: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
      },
      //自己加的文本框
      textarea:''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    upLoad,
    //获取时间
    dateFormat(picker){
      console.log(picker)
      this.queryParams.startTime = picker[0]
      this.queryParams.endTime = picker[1]
    },
    // 文件上传成功后的钩子函数
    handleFileSuccess(response, file, fileList){

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log("正在上传")

      console.log(file);
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径 （url 后台传过来的的上传地址）
      this.imageUrl = file.response.handlePicture;
    },
    uploadChange(file, fileList) {
      this.headFile = file;
      this.headFileList = fileList;
      if(fileList.length==1) {
        let {handlePicture, ...data} = this.rules;
        this.rules = data;
      }
      this.$refs.form.clearValidate('handlePicture');
      this.hideUpload = fileList.length >= this.limitCount;
    },

    /** 查询报警列表 */
    getList() {
      this.loading = true;
      console.log(this.createTime);
      // this.queryParams.createTime = null;
      listData(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipName: null,
        snNum: null,
        regionId: null,
        region: null,
        address: null,
        trigerId: null,
        trigerName: null,
        warningValue: null,
        threshold: null,
        dataType: null,
        handleState: null,
        createTime: null,
        status: null,
        handlePeople: null,
        notes: null,
        handlePicture: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams={
        pageNum: 1,
        pageSize: 10,
        equipName: null,
        handleState: null,
        status: null,
      };
      this.fileList = undefined;//加的是这一行
      this.createTime = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报警";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fileList = undefined;
      const id = row.id
      getData(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "处理报警";
      });
    },
    /** 查看详情按钮操作 */
    handleUpdate1(row) {
      this.reset();
      this.fileList = undefined;
      const id = row.id
      getData(id).then(response => {
        this.fileList = [{ url: response.data.handlePicture}]//加的是这一行
        this.form = response.data;
        this.opens = true;
        this.title = "处理报警";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // this.form.handlePicture = this.imgUpload; // 注：重要(用于添加到数据库)，加的是这一行


      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateData(this.form).then(response => {

              console.log("111"+this.form)
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.formData = null;

              this.form.myIsUpload = null;
            });
          } else {
            addData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除报警编号为"' + ids + '"的数据项？').then(function() {
        return delData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/alarm/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
